package com.test.springboot.springboot3testdemo3.service;

import java.time.Duration;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/9/27-09:01
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Component
public class FixRateBasedThreadPoolMonitorScheduleTask implements SchedulingConfigurer {
  private static final Logger LOGGER =
      LoggerFactory.getLogger(FixRateBasedThreadPoolMonitorScheduleTask.class);
  private long delay = 10000L;

  private ThreadPoolExecutor executor;

  @Autowired
  @Qualifier("threadPoolExecutor")
  public void setExecutor(ThreadPoolExecutor executor) {
    this.executor = executor;
  }

  public void setDelay(long delay) {
    this.delay = delay;
  }

  /**
   * @param taskRegistrar the registrar to be configured
   */
  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    // 动态设置时间循环间隔
    taskRegistrar.addTriggerTask(
        () -> {
          LOGGER.info(
              "========================= \n"
                  + "ThreadPool Size: [{}]\n"
                  + "Active Threads: {}\n"
                  + "Number of Tasks : {}\n"
                  + "Number of Tasks in Queue: {}\n"
                  + "=========================",
              executor.getPoolSize(),
              executor.getActiveCount(),
              executor.getCompletedTaskCount(),
              executor.getQueue().size());
        },
        triggerContext -> {
          // 使PeriodicTrigger触发器，可动态修改循环时间来操作循环规则
          PeriodicTrigger periodicTrigger = new PeriodicTrigger(Duration.ofMillis(delay));
          return periodicTrigger.nextExecution(triggerContext);
        });
  }
}
